package com.gg.verification.controller;

import com.gg.verification.pojo.VerificationPo;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/java/api/v1")
public class CaptchaController {
    @Autowired
    private DefaultKaptcha captchaProducer;
    @Autowired
    private VerificationPo verificationPo;
    @Qualifier("applicationTaskExecutor")
    @Autowired
    private AsyncTaskExecutor taskExecutor;
    @Autowired
    private RedissonClient redissonClient;
//    @GetMapping("/captcha")
//    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        response.setDateHeader("Expires", 0);
//        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
//        response.setHeader("Pragma", "no-cache");
//        response.setContentType("image/jpeg");
//
//        // 获取验证码文本
//        String capText = captchaProducer.createText();
//        // 将验证码文本存入Session
//        HttpSession session = request.getSession();
//        String sessionId = session.getId();
//        Map<String, Object> map = new HashMap<>();
//        map.put(sessionId, capText);
//        verificationPo.setCode(map);
//
//        // 将验证码图片返回给前端
//        BufferedImage bi = captchaProducer.createImage(capText);
//        ServletOutputStream out = response.getOutputStream();
//        try (out) {
//            ImageIO.write(bi, "jpg", out);
//            out.flush();
//        }
//    }

    @GetMapping("/captcha")
    public void handleRequest(HttpServletResponse response,@RequestParam String userAgent) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 获取验证码文本
        String capText = captchaProducer.createText();

        // 将验证码文本存入 Redis，设置过期时间为5分钟

        RBucket<String> bucket = redissonClient.getBucket("captcha:"+ userAgent);
        bucket.set(capText, 5, TimeUnit.MINUTES);


        System.out.println("本次验证码：" + bucket.get());

        // 将验证码图片返回给前端
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        try (out) {
            ImageIO.write(bi, "jpg", out);
            out.flush();
        }
    }

    private void savCode(HttpServletRequest request, String code) {
        // 将验证码文本存入Session
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        Map<String, Object> map = new HashMap<>();
        map.put(sessionId, code);
        verificationPo.setCode(map);
        System.out.println("验证码生成成功: " + verificationPo.getCode());
    }


//    @GetMapping("/captcha")
//    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        int width = 100;
//        int height = 30;
//
//        // 创建一个 BufferedImage 对象，作为验证码图片
//        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//        Graphics g = image.getGraphics();
//
//        // 设置背景色
//        g.setColor(Color.WHITE);
//        g.fillRect(0, 0, width, height);
//
//        // 设置边框
//        g.setColor(Color.BLACK);
//        g.drawRect(0, 0, width - 1, height - 1);
//
//        // 生成随机验证码
//        String captcha = generateRandomCaptcha();
//
//        // 将验证码存储到 Session 中
//        HttpSession session = request.getSession(true);
//        session.setAttribute("captcha", captcha);
//
//        // 绘制验证码字符串
//        g.setColor(Color.BLACK);
//        g.setFont(new Font("Arial", Font.PLAIN, 20));
//        g.drawString(captcha, 10, 20);
//
//        // 输出验证码图片
//        response.setContentType("image/jpeg");
//        response.setHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
//        javax.imageio.ImageIO.write(image, "JPEG", response.getOutputStream());
//        response.getOutputStream().flush();
//    }
//
//    private String generateRandomCaptcha() {
//        // 生成一个包含数字和字母的随机验证码
//        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//        Random random = new Random();
//        StringBuilder captcha = new StringBuilder();
//        for (int i = 0; i < 6; i++) {
//            captcha.append(chars.charAt(random.nextInt(chars.length())));
//        }
//        System.out.println("验证码生成");
//        return captcha.toString();
//    }
}
